package com.atguigu.study.bootredis.zookeeper.lock;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class CuratorLock {

    public static void main(String[] args) {

        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient("10.19.205.97:2181", retryPolicy);
        client.start();

        //测试5个线程的争抢
        int threadCount = 5;
        CountDownLatch latch = new CountDownLatch(threadCount);
        for (int i = 0; i < threadCount; i++) {
            Thread thread = new Thread(() -> {
                try {
                    latch.await();
                    InterProcessMutex lock = new InterProcessMutex(client, "/order");
                    if ( lock.acquire(30, TimeUnit.SECONDS) )
                    {
                        try
                        {
                            // do some work inside of the critical section here
                            System.out.println("我获得了锁！！！"+Thread.currentThread().getName());
                            //模拟处理业务逻辑
                            Thread.sleep(1000 + new Random().nextInt(100) * 10);
                        }
                        finally
                        {
                            lock.release();
                        }
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            thread.start();
            latch.countDown();
        }

    }
}
